package day02;
//读写锁
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Demo7 {
    String name=Thread.currentThread().getName();
    Object data;
    ReentrantReadWriteLock rwLock=new ReentrantReadWriteLock();
    public void read(){   //读取上面数据的方法
        String name = Thread.currentThread().getName();
        try {
            rwLock.readLock().lock();//获取读锁
            System.out.println(name+"模拟开始读取2秒数据"+data);
            Thread.sleep(2000);
            System.out.println(name+"模拟结束读取2秒数据"+data);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            rwLock.readLock().unlock();//释放读锁
        }
    }
    public void write(Object data){//写入数据的方法
        String name = Thread.currentThread().getName();
        try {
            rwLock.readLock().lock();
            System.out.println(name+"模拟开始写入2秒数据"+data);
            this.data=data;
            Thread.sleep(2000);
            System.out.println(name+"模拟结束写入2秒数据"+data);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            rwLock.readLock().unlock();
        }
    }

    public static void main(String[] args) {
        Demo7 d=new Demo7();
        for (int i = 0; i < 3; i++) {
            new Thread(()->{
                for (int j = 0; j < 5; j++) {
                    d.read();
                }
            },"读"+i).start();
            new Thread(()->{
                for (int j = 0; j < 5; j++) {
                    d.write(1.22);
                }
            },"写"+i).start();
        }
    }
}
